<?php

namespace app\agent\model;

use think\facade\Db;

class BalanceWarningConfig
{
    private $table = 'agent_balance_warning_config';

    /**
     * 获取配置
     */
    public function get($agentId)
    {
        $info = Db::name($this->table)
            ->field('status, balance, mobile')
            ->where('agent_id', $agentId)
            ->findOrEmpty();
        if (empty($info)) {
            $info = [
                'status' => 2,
                'balance' => '',
                'mobile' => '',
            ];
        }

        return success('操作成功', $info);
    }

    /**
     * 更新
     */
    public function set($params)
    {
        $id = Db::name($this->table)
            ->where('agent_id', $params['agent_id'])
            ->value('id');

        if (!checkMobile($params['mobile'])) {
            return fail('预警手机号码格式有误');
        }
        
        Db::startTrans();
        try {
            if ($id) {
                Db::name($this->table)
                    ->where('id', $id)
                    ->strict(false)
                    ->update($params);
            } else {
                $id = Db::name($this->table)
                    ->strict(false)
                    ->insertGetId($params);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('操作失败：' . $e->getMessage());
        }

        return success('操作成功');
    }
}
